﻿using FastReport.Utils;
using Infragistics.Documents.Reports.Graphics;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.DataEntify;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Ocsp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;



namespace biaoqian
{
    public partial class Form5 : Form
    {
        Class1 one = new Class1();
        LDhuoyunEntities db = new LDhuoyunEntities();

        public Form5()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                string selectedFolder = folderBrowserDialog1.SelectedPath;
                TraverseFolder(selectedFolder);
            }
        }
        private void TraverseFolder(string folderPath)
        {
            try
            {
                // 获取文件夹中的所有文件  
                string[] files = Directory.GetFiles(folderPath);
                foreach (string file in files)
                {
                    string fileName = System.IO.Path.GetFileNameWithoutExtension(file);
                    int count = db.TBJL.Where(x => x.hd_fhdh == fileName).Count();
                    if (count == 0)
                    {
                        Get_Shipping_note(fileName, file);
                    }
                }

                // 递归遍历子文件夹  
                string[] subFolders = Directory.GetDirectories(folderPath);
                foreach (string subFolder in subFolders)
                {
                    TraverseFolder(subFolder);
                }
            }
            catch (Exception ex)
            {
                // 处理异常，例如文件夹不存在或没有访问权限等  
                MessageBox.Show("遍历文件夹时发生错误: " + ex.Message);
            }
        }
        private void Get_Shipping_note(string name, string file)
        {
            DateTime now = DateTime.Now;
            string currentDateTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            K3CloudApi client = new K3CloudApi();
            //用于记录结果
            StringBuilder Info = new StringBuilder();
            //业务对象标识
            string formId = "SAL_DELIVERYNOTICE";
            //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例
            string fieldKeys = "FBillNo,F_SMGS_BaseProperty7,FReceiveAddress,F_SMGS_KM,F_SMGS_Integer4,FMaterialName,F_SMGS_YFKG,F_SMGS_Decimal1";
            //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
            var ZBLx = name;
            var param = new QueryParam()
            {
                FormId = formId,
                FieldKeys = fieldKeys,
                FilterString = "FBillNo like'%" + ZBLx + "%'",
                TopRowCount = 0,
                StartRow = 0,
                Limit = 120,
                OrderString = "FBillNo",
            };
            //调用接口
            var result = client.ExecuteBillQuery(param.ToJson());

            if (dataGridView1.Columns.Count != 0)
            {
                dataGridView1.Columns.Clear();
            }
            /* JsonSerializerSettings settings = new JsonSerializerSettings();
             string jsongStr = JsonConvert.SerializeObject(result, settings);*/
            //转换成标准文档并遍历
            DataTable dataTable = one.ERP_hdpp();
            foreach (var item in result)
            {
                bool index = false;
                if (dataTable.Rows.Count == 0)
                {
                    dataTable.Rows.Add(item[0], item[1], file, name);
                }
                else
                {
                    foreach (DataRow obj in dataTable.Rows)
                    {
                        string a = obj.ItemArray[0].ToString();
                        string b = item[0].ToString();
                        if (b.Contains(a))
                        {
                            index = true;
                            break;

                        }
                    }
                    if (index == false)
                    {
                        dataTable.Rows.Add(item[0], item[1], file, name);
                    }

                }

            }
            dataGridView1.DataSource = dataTable;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dataGridView in dataGridView1.Rows)
            {
                string FBillNo = dataGridView.Cells[0].ToString();
                string file = dataGridView.Cells[2].Value.ToString();
                string filename = dataGridView.Cells[3].Value.ToString();

                UploadTest(file, filename, FBillNo);
                TBJL tb = new TBJL()
                {
                    hd_fhdh = dataGridView.Cells[0].Value.ToString()
                };
                db.TBJL.Add(tb);
            }
        }


        public void UploadTest(string file, string filename, string FBillNo)
        {
            K3CloudApi client = new K3CloudApi();
            // 上传文件
            DateTime now = DateTime.Now;
            string currentDateTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            var filePath = file;
            string fileName = System.IO.Path.GetFileName(filePath); // 获取文件名  
            var fileBytes = File.ReadAllBytes(filePath);
            var fileBase64String = Convert.ToBase64String(fileBytes);
            string file_extension = System.IO.Path.GetExtension(filePath);
            FileInfo fileInfo = new FileInfo(filePath);
            int file_size_kb = 0;
            if (fileInfo.Exists)
            {
                long file_size_bytes = fileInfo.Length;
                file_size_kb = (int)(file_size_bytes / 1024.0); // 转换为KB  

                Console.WriteLine("File size: " + file_size_kb.ToString("F2") + " KB"); // 保留两位小数  
            }
            string jsonStr0 = "{\"CreateOrgId\": \"0\",\"Number\": \"" + filename + "\",\"Id\": \"\",\"IsSortBySeq\": \"false\"}";
            var id = client.View("SAL_DELIVERYNOTICE", jsonStr0);

            int startIndex = id.IndexOf("Id\":") + "Id\":".Length; // 找到"World"的索引并加上其长度  
            string substring = id.Substring(startIndex, 6); // 从"World"后面开始，截取长度为4的子字符串  
            Console.WriteLine(substring); // 输出 "This"

            //var data = JsonConvert.SerializeObject(dataObj);
            


            string jsons = "{\r\n        \"Model\": {\r\n                \"FAttachmentName\": \""+ fileName + "\",\r\n            \"FBillType\": \"SAL_DELIVERYNOTICE\",\r\n            \"FInterID\": \""+ substring + "\",\r\n            \"FBillNo\": \""+ filename + "\",\r\n            \"FAttachmentSize\": "+ file_size_kb + ",\r\n            \"FAttachment\":\""+ fileBase64String + "\",\r\n            \"FFILESTORAGE\":0,\r\n            \"FExtName\": \""+ file_extension + "\",\r\n            \"FEntryinterId\": \"-1\",\r\n            \"FEntrykey\": \" \",\r\n            \"FaliasFileName\": \""+ fileName + "\",\r\n            \"FCreateMen\": {\r\n                    \"FUserID\": \"100162\"\r\n            },\r\n            \"FCreateTime\": \""+ currentDateTime + "\"\r\n        }\r\n        }";

            var data2 = client.Save("BOS_Attachment", jsons);
        
            //FAttachmentName附件名称
            //FBillType 具体的单据标识，示例为付款单
            //FInterID上传附件的单据内码
            //FBillNo单据编码
            //FAttachmentSize附件大小单位KB
            //FAttachment具体的附件内容，转base64以后的
            //FFILESTORAGE附件存储类型，1标识文件服务器存储 ,0标识数据库
            //FExtName附件扩展名
            //FEntryinterId单据体内码，如果是单据头附件的话，传 - 1
            //FEntrykey单据体标识，如果是单据头的附件的话，需要传一个空格。
            
        }

        /// <summary>
        /// 附件上传（小于6M的文件可用）
        /// </summary>
        [TestMethod]
        public void UploadTest2(string file, string filename, string FBillNo)
        {
            K3CloudApi client = new K3CloudApi();
            // 给采购订单上传单据头附件
            var formId = "SAL_DELIVERYNOTICE";

            string jsonStr0 = "{\"CreateOrgId\": \"0\",\"Number\": \"" + filename + "\",\"Id\": \"\",\"IsSortBySeq\": \"false\"}";
            var id2 = client.View("SAL_DELIVERYNOTICE", jsonStr0);

            int startIndex = id2.IndexOf("Id\":") + "Id\":".Length; // 找到"World"的索引并加上其长度  
            string substring = id2.Substring(startIndex, 6); // 从"World"后面开始，截取长度为4的子字符串  

            var billNo = filename;
            var id = substring; // SELECT * FROM T_PUR_POORDER WHERE FBILLNO='CGDD001939'
            var fileName = System.IO.Path.GetFileName(file); // 获取文件名  
            var filePath = file;
            var fileBytes = File.ReadAllBytes(filePath);
            var fileBase64String = Convert.ToBase64String(fileBytes);
            /*
            {
                "FileName": "8.png",
                "FormId": "PUR_PurchaseOrder",
                "IsLast": "true",
                "InterId": "107361",
                "BillNo": "CGDD001939",
                "AliasFileName": "8.png",
                "FileId": "914ad20995d34178b34ec264b23f5f52",
                "SendByte": "iVBORw0KGgrkJggg=="
            }
                         */
            var dataObj = new
            {
                FileName = fileName,
                FormId = formId,
                IsLast = "true",
                InterId = id, // SELECT * FROM T_PUR_POORDER WHERE FBILLNO='CGDD001939'
                BillNo = billNo,
                AliasFileName = fileName,
                SendByte = fileBase64String
            };

            var data = JsonConvert.SerializeObject(dataObj);
            //Console.WriteLine(data);
            var result = client.AttachmentUpLoad(data);
            Console.WriteLine(result);
            var responseDto = ResponseDto.Parse(result);
            Assert.IsTrue(responseDto != null);
            Assert.IsTrue(responseDto.Result != null);
            Assert.IsTrue(responseDto.Result.ResponseStatus != null);
            Assert.IsTrue(responseDto.Result.ResponseStatus.IsSuccess);
            Assert.IsTrue(!string.IsNullOrWhiteSpace(responseDto.Result.FileId));
            Console.WriteLine(responseDto.Result.FileId);
        }
        /// <summary>
        /// 附件分块上传（大于6M的文件可用）
        /// </summary>
        [TestMethod]
        public void BlockUploadTest()
        {
            K3CloudApi client = new K3CloudApi();
            // 给采购订单上传单据头附件
            var formId = "PUR_PurchaseOrder";
            var billNo = "CGDD001939";
            var id = "107361"; // SELECT * FROM T_PUR_POORDER WHERE FBILLNO='CGDD001939'
            var fileName = "6.png";
            var filePath = @"C:\Users\Public\Pictures\Sample Pictures\6.png";
            var blockSize = 1024 * 1024; // 分块大小：1M
            var fileId = string.Empty;
            using (var fsRead = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                if (fsRead.Length <= 0)
                {
                    throw new Exception("文件内容不允许为空。");
                }
                while (true)
                {
                    // 放里面声明，第一次填入完整字节数据，第二次若只填充一部分，此时后面的直接数组并不会被清空。
                    var content = new byte[blockSize];
                    int size = fsRead.Read(content, 0, content.Length);
                    if (size == 0)
                    {
                        break;
                    }
                    var isLast = (size != blockSize);
                    var uploadBytes = new byte[size];
                    Array.Copy(content, uploadBytes, size);
                    var fileBase64String = Convert.ToBase64String(uploadBytes);
                    /*
{
    "FileName": "8.png",
    "FormId": "PUR_PurchaseOrder",
    "IsLast": "true",
    "InterId": "107361",
    "BillNo": "CGDD001939",
    "AliasFileName": "8.png",
    "FileId": "914ad20995d34178b34ec264b23f5f52",
    "SendByte": "iVBORw0KGgrkJggg=="
}
                     */
                    var dataObj = new
                    {
                        FileName = fileName,
                        FormId = formId,
                        IsLast = isLast.ToString(),
                        InterId = id,
                        BillNo = billNo,
                        AliasFileName = fileName,
                        FileId = fileId,
                        SendByte = fileBase64String
                    };
                    var data = JsonConvert.SerializeObject(dataObj);
                    //Console.WriteLine(data);
                    var result = client.AttachmentUpLoad(data);
                    Console.WriteLine(result);
                    var responseDto = ResponseDto.Parse(result);
                    Assert.IsTrue(responseDto != null);
                    Assert.IsTrue(responseDto.Result != null);
                    Assert.IsTrue(responseDto.Result.ResponseStatus != null);
                    Assert.IsTrue(responseDto.Result.ResponseStatus.IsSuccess);
                    Assert.IsTrue(!string.IsNullOrWhiteSpace(responseDto.Result.FileId));
                    Console.WriteLine(responseDto.Result.FileId);
                    fileId = responseDto.Result.FileId; // 第一个分块上传时，FileId是空，从第二个分块开始，FileId不能再为空。
                    if (isLast)
                    {
                        break;
                    }
                }
            }
            Assert.IsTrue(true);
        }
        #region ResponseDto
        /// <summary>
        /// 响应数据包
        /// </summary>
        public class ResponseDto
        {
            #region method
            /// <summary>
            /// 将当前对象序列化为Json字符串
            /// </summary>
            /// <returns></returns>
            public virtual string ToJson()
            {
                return JsonConvert.SerializeObject(this);
            }
            /// <summary>
            /// 将Json字符串反序列化为指定对象
            /// </summary>
            /// <param name="json"></param>
            /// <returns></returns>
            public static ResponseDto Parse(string json)
            {
                return JsonConvert.DeserializeObject<ResponseDto>(json);
            }
            #endregion
            #region property
            /// <summary>
            /// 响应结果
            /// </summary>
            public ResponseResult Result { get; set; }
            #endregion
            #region class
            public class ResponseResult
            {
                public string Id { get; set; }
                public string FileId { get; set; }
                public ResponseResultStatus ResponseStatus { get; set; }
                public class ResponseResultStatus
                {
                    public string MsgCode { get; set; }
                    public bool IsSuccess { get; set; }
                    public string ErrorCode { get; set; }
                    public System.Collections.Generic.IList<ResponseMessage> Errors { get; set; }
                    public System.Collections.Generic.IList<ResponseMessage> SuccessMessages { get; set; }
                    public System.Collections.Generic.IList<SuccessEntity> SuccessEntitys { get; set; }
                    public class ResponseMessage
                    {
                        public string FieldName { get; set; }
                        public string Message { get; set; }
                        public int DIndex { get; set; }
                    }
                    public class SuccessEntity
                    {
                        public string Id { get; set; }
                        public string Number { get; set; }
                        public string BillNo { get; set; }
                        public int DIndex { get; set; }
                    }
                }
                #endregion
            }
            #endregion
        }

    }
    
}

